package cn.tedu.egweibo.controller;

import cn.tedu.egweibo.mapper.UserMapper;
import cn.tedu.egweibo.pojo.dto.UserLoginDTO;
import cn.tedu.egweibo.pojo.dto.UserRegDTO;
import cn.tedu.egweibo.pojo.entity.User;
import cn.tedu.egweibo.pojo.vo.UserVO;
import cn.tedu.egweibo.result.JsonResult;
import cn.tedu.egweibo.result.Status;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpSession;
import java.util.Date;
@Slf4j
@RestController
@RequestMapping("/users")
@Api(tags = "用户模块")
public class UserController {
    @Autowired
    private UserMapper userMapper;
    @PostMapping("/reg")
    @ApiOperation("用户注册")
    public int regUser(@RequestBody UserRegDTO userRegDTO){

        log.trace("UserController:regUser()");
        log.info("开始处理用户注册");
        log.debug(userRegDTO.toString());
        String username = userRegDTO.getUsername();

        if(userMapper.selectByUsername(username)!=null){
            return 2;
        }

        User user = new User();
        BeanUtils.copyProperties(userRegDTO,user);
        user.setCreated(new Date());
        log.debug(user.toString());
        userMapper.insert(user);
        return 1;
    }
    @PostMapping("/login")
    @ApiOperation("用户登录")
    public int login(UserLoginDTO userLoginDTO){
        User user = userMapper.selectByUsername(userLoginDTO.getUsername());
        if(user!=null){
           if(user.getPassword().equals(userLoginDTO.getPassword())){
               return 1;//成功
           }else{
               return 2;//密码错误
           }
        }
        return 3;//用户名错误
    }
    @ApiOperation("查看登录用户信息")
    @GetMapping("/currentUser")
    public JsonResult currentUser(@ApiIgnore HttpSession session){
        User user = (User)session.getAttribute("user");
        System.out.println("当前登录用户信息为:"+user);
        if(user==null){
            return new JsonResult(Status.NOT_LOGIN);
        }
        UserVO userVO = new UserVO();
        BeanUtils.copyProperties(user,userVO);
        return JsonResult.success(userVO);
    }
    @GetMapping("/logout")
    @ApiOperation("用户登出")
    public JsonResult logout(@ApiIgnore HttpSession session){
        session.removeAttribute("user");
        return JsonResult.success();
    }


}
